package com.colin.userservice.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONObject;
import com.colin.bean.User;
import com.colin.bean.UserFollow;
import com.colin.response.R;
import com.colin.userservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/auth")
    public R<User> doLogin(@RequestBody User user) {
        return userService.doLogin(user);
    }

    @PostMapping
    public R<Boolean> doRegister(@RequestBody JSONObject jsonObject) {
        User user = new User();
        String phoneNum = jsonObject.getStr("phoneNum");
        String password = jsonObject.getStr("password");
        user.setPhoneNum(phoneNum);
        user.setPassword(password);
        String smsCode = jsonObject.getStr("smsCode");
        return userService.doRegister(user, smsCode);
    }

    @PostMapping("/logout")
    public R<Boolean> doLogout() {
        StpUtil.logout();
        return R.ok(true);
    }

    @GetMapping("/details")
    public R<User> getUser() {
        return userService.getUserDetail();
    }

    @PostMapping("/code")
    public R<String> doCode(@RequestBody JSONObject jsonObject) {
        String phoneNum = jsonObject.getStr("phoneNum");
        return userService.doCode(phoneNum);
    }

    @GetMapping("/follow")
    public R<List<User>> getFollow() {
        return userService.getFollowList();
    }

    @PostMapping("/follow")
    public R<Boolean> doFollow(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getStr("userId");
        return userService.doFollow(userId);
    }

    @DeleteMapping("/follow")
    public R<Boolean> doUnFollow(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getStr("userId");
        return userService.doUnFollow(userId);
    }

    @GetMapping("/search")
    public R<List<User>> getSearch(@RequestBody JSONObject jsonObject) {
        String description = jsonObject.getStr("description");
        return userService.getSearch(description);
    }

    @PostMapping("/update")
    public R<Boolean> doUpdate(@RequestBody User user) {
        return userService.doUpdate(user);
    }

    @PostMapping("/avatar")
    public R<Boolean> doAvatar(@RequestParam("avatar") MultipartFile avatar) throws IOException {
        return userService.uploadAvatar(avatar);
    }

    @GetMapping("/follow/status")
    public R<UserFollow> getFollowStatus(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getStr("userId");
        return userService.getFollowStatus(userId);
    }
}
